
const { article: ArticleModal } = require('../db');
const { analysisToken } = require('../util/common')

// 新增文章
const addArticleRoute = async ctx => {
    const { title, content } = ctx.request.body;
    // 获取解密数据
    let id = analysisToken(ctx.headers.authorization);
    if (!title || !content) {
        ctx.body = { message: '标题或内容不能为空', result: false }
        return
    }
    // 往数据库中添加
    try {
        await ArticleModal.createData({
            title,
            content,
            user_id: id
        });
        ctx.body = { message: '内容新增成功', result: true };
    } catch (error) {
        throw error
    }
};

// 获取所有文章
const getArticleRoute = async ctx => {
    // 获取解密数据
    let id = analysisToken(ctx.headers.authorization);
    const result = await ArticleModal.findAll({
        raw: true,
        where: {
            user_id: id
        }
    });
    ctx.body = { message: '', result };
}

// 删除文章
const deleteArticleRoute = async ctx => {
    // 获取解密数据
    let id = analysisToken(ctx.headers.authorization);
    const { id: articleId } = ctx.params;
    const data = await ArticleModal.find({ id: articleId });
    if (!data) {
        return ctx.body = { message: '未找到该数据', result: false };
    }
    try {
        await ArticleModal.destroy({ where: { id: articleId } });
        ctx.body = { message: '', result: true };
    } catch (error) {
        ctx.body = { message: error, result: false };
    }
}

module.exports = [
    { method: 'post', requestUrl: '/add', callback: addArticleRoute },
    { method: 'get', requestUrl: '/list', callback: getArticleRoute },
    { method: 'delete', requestUrl: '/delete/:id', callback: deleteArticleRoute },
]